﻿using System.Web;
using System.Xml.Linq;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Web.Caching;
using System;

namespace SusuCMS.Globalization
{
    public static class LocalizeExtension
    {
        public static string Localize(this string source)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                return string.Empty;
            }

            var cultureName = Thread.CurrentThread.CurrentUICulture.Name;

            var dictionary = (Dictionary<string, string>)HttpRuntime.Cache[cultureName];
            if (dictionary == null)
            {
                dictionary = new Dictionary<string, string>();
                var filePath = HttpContext.Current.Server.MapPath(string.Format("~/App_GlobalResources/{0}.resx", cultureName));

                try
                {
                    var doc = XDocument.Load(filePath);
                    foreach (var item in doc.Descendants("data"))
                    {
                        dictionary.Add(item.Attribute("name").Value.ToLower(), item.Element("value").Value);
                    }
                }
                catch
                {
                    // do nothing
                }

                // make cache
                var dependency = new CacheDependency(filePath);
                HttpRuntime.Cache.Insert(cultureName, dictionary, dependency, Cache.NoAbsoluteExpiration, TimeSpan.Zero);
            }

            var key = source.ToLower();

            return dictionary.ContainsKey(key) ? dictionary[key] : source;
        }
    }
}
